import math
import random
import sys
import time

from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By

from libs import config
from libs.action import WebDriverAction
from libs.game import Game
from libs.image import ImageTool
from libs.log import Log
from libs.movement import Movement
from libs.task_helper import TaskHelper
from libs.trade_helper import TradeHelper
from libs.window import AdsWindow


def decide_cooking_item():
    jam_name = 'Popberry Jam'
    flour_name = 'Grainbow Flour'
    jam_count = game.get_backpack_qty(jam_name)
    flour_count = game.get_backpack_qty(flour_name)
    log.info(f"flour={flour_count}, jam={jam_count}")
    if jam_count < 32 * 3:
        return 'popberry_jam_12'
    if flour_count < 32 * 2:
        return 'grainbow_flour_12'
    return loaf_item_key


def collect(offset_x, offset_y):
    global tb_loc
    tb_x, tb_y = tb_loc
    if action.hover_bubble_text_is(tb_x + offset_x, tb_y + offset_y, 'Ready to Collect'):
        action.click()
        time.sleep(0.5)


def cook(offset_x, offset_y):
    global tb_loc
    tb_x, tb_y = tb_loc
    if action.hover_bubble_text_is(tb_x + offset_x, tb_y + offset_y, 'Add 1 Log'):
        game.use_backpack_item(log_index)
        time.sleep(0.5)
        action.click()
        action.escape()
        time.sleep(0.5)
    if action.hover_bubble_text_is(tb_x + offset_x, tb_y + offset_y, 'Click to Cook'):
        action.click()
        time.sleep(1)
        opt = action.find_element(By.XPATH, f"//span[text()='{cooking_item_name}']", cooking_item_name, 3)
        if opt is None:
            action.escape()
            time.sleep(1)
            action.click()
            opt = action.find_element(By.XPATH, f"//span[text()='{cooking_item_name}']", cooking_item_name, 10)
        opt.click()
        action.click_by_offset(440, 540)
        time.sleep(0.5)
        action.escape()
        time.sleep(0.5)
        return 1
    return 0


def drink_popberry_wine(energy_target):
    log.info(f"drink energy start: energy={game.get_energy()}, need {energy_target}")
    home_loc = action.goto_spec()
    game.open_backpack()
    wine_loc = image_tool.find_target('popberry_wine.png')
    if wine_loc is None:
        log.info('popberry wine not found')
    else:
        wine_x, wine_y = wine_loc
        action.click_by_offset(wine_x + 20, wine_y + 20)

        before_drink_energy = game.get_energy()
        no_effect_count = 0
        while True:
            if energy_target - game.get_energy() < 77:
                log.debug('energy full')
                action.escape()
                break
            home_x, home_y = home_loc
            action.move_by_offset(home_x + 45, home_y + 180)
            action.click()
            time.sleep(1)
            after_drink_energy = game.get_energy()
            if after_drink_energy - before_drink_energy > 10:
                before_drink_energy = after_drink_energy
                continue
            else:
                # 体力没增加
                log.debug('drink no effect')
                no_effect_count += 1
                if no_effect_count > 2:
                    action.escape()
                    break
                continue
    log.info(f"drink energy end: energy={game.get_energy()}")
    time.sleep(1)
    game.close_backpack()

if __name__ == "__main__":
    parser = TaskHelper.default_args_parser('Cooking Popberry')
    args = parser.parse_args()
    task_helper = TaskHelper.from_args(args)

    user_id = args.user_id
    log = Log(user_id)
    try:
        # 启动窗口
        driver = AdsWindow(user_id).open(False)
        action = WebDriverAction(driver, debug=False)
        movement = Movement(driver)
        ac = ActionChains(driver)
        image_tool = ImageTool(driver)
        game = Game(driver, user_id)
        # 进入游戏
        game.enter_game()
        game.collect_mail()
        game.snapshot(user_id, 'before cooking')
        log.info('cooking start')

        loaf_item_key = 'popberry_loaf'
        offset_x1s = [-460, -330]
        offset_x2s = [-200, -70]
        offset_ys = [-155, -30, 110]

        # 先收集再判断做什么
        action.goto_task_board()
        movement.keep_move_left(2.2)
        tb_loc = image_tool.find_target('task_board.png')
        for x in offset_x1s:
            for y in offset_ys:
                collect(x, y)

        movement.keep_move_right(1)
        tb_loc = image_tool.find_target('task_board.png')
        for x in offset_x2s:
            for y in offset_ys:
                collect(x, y)

        cooking_item_key = decide_cooking_item()
        log.info(f'cook {cooking_item_key}')
        cooking_item = config.get_cooking_item(cooking_item_key)
        cooking_item_name = cooking_item.get('name')
        is_loaf = cooking_item_key == loaf_item_key

        # 买原料
        buy_items = {}
        log_item_name = 'Whittlewood Log'
        log_index, log_qty = game.get_backpack_index_and_qty(log_item_name)
        if log_qty < 20:
            buy_items[log_item_name] = 99 - log_qty

        wine_item_name = 'Popberry Wine'
        wine_qty = game.get_backpack_qty(wine_item_name)
        # if wine_qty < 5:
        #     buy_items[wine_item_name] = 10

        if not is_loaf:
            need_items = cooking_item.get('items', {})
            for item_name in need_items:
                need_qty = need_items.get(item_name) * (8 if cooking_item_key == 'popberry_jam_12' else 7)
                bp_qty = game.get_backpack_qty(item_name)
                if need_qty > bp_qty:
                    buy_items[item_name] = need_qty - bp_qty

        trade_helper = TradeHelper(driver, user_id)
        if len(buy_items) > 0:
            trade_helper.goto_buy_position()
            filter_input = trade_helper.open_market_buy()
            for buy_item_name in buy_items:
                buy_item_qty = buy_items.get(buy_item_name)
                trade_helper.market_buy_item(filter_input, buy_item_name, buy_item_qty)
            action.escape()
            time.sleep(0.5)
            action.escape()
            time.sleep(1)

            # 卖成品
            trade_helper.buy_to_sell()
            trade_helper.open_shop_sell()
            cooking_loaf = config.get_cooking_item(loaf_item_key)
            sell_items = {cooking_loaf.get('sell_item_name'): cooking_loaf.get('min_price'), 'Blue Grumpkin Loaf': 100}
            my_coin = game.get_coin()
            for sell_item_name in sell_items:
                qty = game.get_backpack_qty(sell_item_name)
                if qty > 0:
                    min_price = sell_items.get(sell_item_name)
                    if my_coin < 10000:
                        # 如果余额小于1万，则最低限价再降低20%
                        min_price = int(min_price * 0.8)
                    trade_helper.sell_item(sell_item_name, qty, min_price)
            time.sleep(0.5)
            action.escape()
            time.sleep(0.5)

        # 做烹饪
        energy_cost = cooking_item.get('energy_cost')
        max_make_count = 32
        if not is_loaf:
            max_make_count = 8 if cooking_item_key == 'popberry_jam_12' else 7

        max_energy = min(1000, max_make_count * energy_cost)
        if max_energy - game.get_energy() >= 77:
            # 喝酒
            drink_popberry_wine(max_energy)

        make_count = min(max_make_count, math.floor(game.get_energy() / energy_cost))
        action.goto_task_board()
        movement.keep_move_left(2.2)


        finish_count = 0
        for _ in range(3):
            # 点火，烹饪
            tb_loc = image_tool.find_target('task_board.png')
            for x in offset_x1s:
                for y in offset_ys:
                    collect(x, y)
                    if finish_count < make_count:
                        finish_count += cook(x, y)

            movement.keep_move_right(1)
            ac.reset_actions()
            tb_loc = image_tool.find_target('task_board.png')
            for x in offset_x2s:
                for y in offset_ys:
                    collect(x, y)
                    if finish_count < make_count:
                        finish_count += cook(x, y)
            log.info(f'{finish_count}/{make_count} made')
            if is_loaf:
                movement.keep_move_left(1)
                wait_seconds = cooking_item.get('wait_seconds') - 70
                if finish_count >= make_count:
                    break
                else:
                    log.info(f'wait {wait_seconds} seconds')
                    time.sleep(wait_seconds)
                    game.enter_game()
            else:
                break

        # 去睡觉
        movement.keep_move_right(3.5)
        bed_loc = image_tool.find_target('bed.png')
        if bed_loc:
            bed_x, bed_y = bed_loc
            action.move_by_offset(bed_x - 80, bed_y - 40)
            for _ in range(4):
                target = action.find_element(By.CLASS_NAME, 'LookAtBubble_lookAtBubble___pd4a', 'LookAtBubble', 1)
                if target is None:
                    time.sleep(0.5)
                    continue
                elif target.text == 'Sleep to Gain Energy':
                    log.info('sleep')
                    action.click()
                    time.sleep(70)
                    break
                else:
                    continue

        game.snapshot(user_id, 'after_cooking')

        task_helper.cooking_pop(delay_seconds=random.randint(60 * 60 * 6, 60*60*8))
        task_helper.task_success()

    except Exception as e:
        log.info('error occurred')
        task_helper.task_fail()
        task_helper.cooking_pop(retry=True)
        raise e
